package com.dios.mirage.component.fields;

import net.rim.device.api.system.Display;
import net.rim.device.api.system.EncodedImage;
import net.rim.device.api.ui.Field;
import net.rim.device.api.ui.TouchEvent;

import com.dios.mirage.component.view.The360View;

public class TurnImageField extends FocusableField {

	private The360View view;
	int _xTouch = 0;
	private boolean isTouchOutside;

	public TurnImageField(The360View view) {
		super(null, Field.FOCUSABLE);
		this.view = view;
	}

	protected void layout(int width, int height) {
		super.layout(Display.getWidth(), height);
	}

	protected boolean navigationClick(int status, int time) {
		if (isTouchOutside)
			fieldChangeNotify(0);
		return true;
	}

	protected boolean touchEvent(TouchEvent touchEvent) {
		int event = touchEvent.getEvent();
		isTouchOutside = touchEvent.getX(1) < 0 || touchEvent.getX(1) > getWidth()
				|| touchEvent.getY(1) < 0 || touchEvent.getY(1) > getHeight();
		if (!isTouchOutside) {
			if (event == TouchEvent.DOWN) {
				_xTouch = touchEvent.getX(1);
			} else if (event == TouchEvent.MOVE) {
				if (_xTouch < touchEvent.getX(1)) {
					view.iImage--;
					if (view.iImage == -1)
						view.iImage = view.imageSize - 1;
					this.setImage((EncodedImage) view.listImage
							.elementAt(view.iImage));
				} else if (_xTouch > touchEvent.getX(1)) {
					view.iImage++;
					if (view.iImage == view.imageSize)
						view.iImage = 0;
					this.setImage((EncodedImage) view.listImage
							.elementAt(view.iImage));
				}
				_xTouch = touchEvent.getX(1);
			}
		}
		return super.touchEvent(touchEvent);
	}

	protected boolean navigationMovement(int dx, int dy, int status, int time) {
		if (dx > 0) {
			view.iImage--;
			if (view.iImage == -1)
				view.iImage = view.imageSize - 1;
			this.setImage((EncodedImage) view.listImage.elementAt(view.iImage));
		} else if (dx < 0) {
			view.iImage++;
			if (view.iImage == view.imageSize)
				view.iImage = 0;
			this.setImage((EncodedImage) view.listImage.elementAt(view.iImage));
		}
		return super.navigationMovement(dx, dy, status, time);
	}

}
